// app/admin/users/page.jsx
'use client';

import { useState, useEffect } from 'react';
import api from "../../apis/api";
import { toast } from 'react-toastify';
export default function UsersPage() {
    const [users, setUsers] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [newUser, setNewUser] = useState({
        username: '',
        is_active: true,
        is_admin: false,
        points: 0,
        password: '',
        email: ''
    });

    useEffect(() => {
        fetchUsers();
    }, []);

    const fetchUsers = async () => {
        try {
            const response = await api.get('/api/v1/admin/users');
            if (response.status === "success") {
                setUsers(response.data);
            }
        } catch (error) {
            console.error('获取用户数据失败:', error);
        }
    };

    const handleInputChange = (e) => {
        const { name, value, type, checked } = e.target;
        setNewUser(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await api.post('/api/v1/admin/users/', newUser);
            console.log('response', response);
            if (response.status === "status") {
                console.log('用户创建成功');
                setShowModal(false);
                fetchUsers();
            } else {
                console.log('用户创建失败1');
                toast.error('用户创建失败2' + response.message);
            }
        } catch (error) {
            toast.error('用户创建失败' + error);
            console.error('创建用户失败3:', error);
        }
    };

    return (
        <div className="p-4 space-y-4">
            <h1 className="text-2xl font-bold text-gray-800">用户管理</h1>
            <div className="flex justify-between">
                <button onClick={fetchUsers} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                    获取用户数据
                </button>
                <button onClick={() => setShowModal(true)} className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                    添加用户
                </button>
            </div>
            <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
                <tr>
                    <th scope="col" className="px-6 py-3">ID</th>
                    <th scope="col" className="px-6 py-3">用户名</th>
                    <th scope="col" className="px-6 py-3">是否管理员</th>
                    <th scope="col" className="px-6 py-3">创建时间</th>
                    <th scope="col" className="px-6 py-3">最后更新时间</th>
                    <th scope="col" className="px-6 py-3">是否活跃</th>
                    <th scope="col" className="px-6 py-3">积分</th>
                </tr>
                </thead>
                <tbody>
                {users.map((user) => (
                    <tr key={user.id} className="bg-white border-b dark:bg-gray-900 dark:border-gray-700">
                        <th scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
                            {user.id}
                        </th>
                        <td className="px-6 py-4">{user.username}</td>
                        <td className="px-6 py-4">{user.is_admin ? '是' : '否'}</td>
                        <td className="px-6 py-4">{user.created_at}</td>
                        <td className="px-6 py-4">{user.updated_at}</td>
                        <td className="px-6 py-4">{user.is_active ? '是' : '否'}</td>
                        <td className="px-6 py-4">{user.points}</td>
                    </tr>
                ))}
                </tbody>
            </table>

            {showModal && (
                <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full">
                    <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                        <h3 className="text-lg font-bold mb-4">添加新用户</h3>
                        <form onSubmit={handleSubmit}>
                            <div className="mb-4">
                                <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="username">
                                    用户名
                                </label>
                                <input
                                    type="text"
                                    id="username"
                                    name="username"
                                    value={newUser.username}
                                    onChange={handleInputChange}
                                    className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                    required
                                />
                            </div>
                            <div className="mb-4">
                                <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="email">
                                    邮箱
                                </label>
                                <input
                                    type="email"
                                    id="email"
                                    name="email"
                                    value={newUser.email}
                                    onChange={handleInputChange}
                                    className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                    required
                                />
                            </div>
                            <div className="mb-4">
                                <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
                                    密码
                                </label>
                                <input
                                    type="password"
                                    id="password"
                                    name="password"
                                    value={newUser.password}
                                    onChange={handleInputChange}
                                    className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                    required
                                />
                            </div>
                            <div className="mb-4">
                                <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="points">
                                    积分
                                </label>
                                <input
                                    type="number"
                                    id="points"
                                    name="points"
                                    value={newUser.points}
                                    onChange={handleInputChange}
                                    className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                />
                            </div>
                            <div className="mb-4">
                                <label className="flex items-center">
                                    <input
                                        type="checkbox"
                                        name="is_active"
                                        checked={newUser.is_active}
                                        onChange={handleInputChange}
                                        className="mr-2"
                                    />
                                    <span className="text-gray-700 text-sm font-bold">是否活跃</span>
                                </label>
                            </div>
                            <div className="mb-4">
                                <label className="flex items-center">
                                    <input
                                        type="checkbox"
                                        name="is_admin"
                                        checked={newUser.is_admin}
                                        onChange={handleInputChange}
                                        className="mr-2"
                                    />
                                    <span className="text-gray-700 text-sm font-bold">是否管理员</span>
                                </label>
                            </div>
                            <div className="flex items-center justify-between">
                                <button
                                    type="submit"
                                    className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                                >
                                    提交
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setShowModal(false)}
                                    className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                                >
                                    取消
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}